#!/usr/bin/python
#coding:utf-8
'''
基于scikit-learn实现Cart决策树算法
'''

from sklearn import tree
from sklearn.datasets import load_iris
import pandas
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
import pickle

urlSave=".\work\src\python\eci\ecicikit.sav"
#保存和导入机器学习模型
def saveDataToStary():
	
	#两种保存方式，任选其一

	url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
	names= ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
	dataframe = pandas.read_csv(url,names=names)
	array = dataframe.values
	X=array[:,0:8]
	Y = array[:,8]
	test_size=0.33
	seed =7
	X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed)

	model = LogisticRegression()
	model.fit(X_train,Y_train)
	#保存模型到文件
	filename='data.sav'
	pickle.dump(model,open(filename,'wb'))

	#加载模型
	load_model = pickle.load(open(filename,'rb'))
	#与测试和真是值比较
	result = load_model.score(X_test,Y_test)
	print(result)

def pic():
	from sklearn import datasets
	from sklearn.tree import DecisionTreeClassifier 

	from IPython.display import Image
	from sklearn import tree
	import pydotplus
	import os 

	os.environ["PATH"] += os.pathsep + 'E:/python-space/tool/release/bin'

	#载入sciki-learn决策
	iris = datasets.load_iris()
	clf = tree.DecisionTreeClassifier()
	clf = clf.fit(iris.data, iris.target)

	#存储模型到文件 iris.dot
	# with open("iris.dot", 'w') as f:
	#     f = tree.export_graphviz(clf, out_file=f)

	#算法模型图生成pdf文件
	# dot_data = tree.export_graphviz(clf, out_file=None) #不指定类别颜色
	dot_data = tree.export_graphviz(clf, out_file=None,  #指定不同类别颜色
	                         feature_names=iris.feature_names,  
	                         class_names=iris.target_names,  
	                         filled=True, rounded=True,  
	                         special_characters=True) 

	graph = pydotplus.graph_from_dot_data(dot_data) 
	graph.write_png("sciki.png")
	# graph.write_pdf("sciki.pdf")
	# Image(graph.create_png()) 

def test():
	# 记录训练样本  [样本，特征]
	x=[[3,4,1],[3,3,2],[5,6,2],[6,4,7]]
	#记录训练样本类标签  [样本]
	y=[0,0,1,1]
	
	# url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
	# names= ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
	# dataframe = pandas.read_csv(url,names=names)
	# array = dataframe.values
	# x=array[:,0:8]  # 截取0到8位为特征 不包括第八位
	# y = array[:,8]  #截取第8位为 结论
	# print x[0]

	#创建决策树
	clf=tree.DecisionTreeClassifier(criterion='entropy') #默认Gini基尼不纯度 entropy 采用ID3算法criterion='entropy'
	#拟合
	clf =clf.fit(x,y)
	#输出每个特征的重要程度
	print("特征重要程度",clf.feature_importances_)

	#结果预测
	fen=clf.predict([[5,3,6]])
	print("样本分类",fen)

	# #每个分类的概率预测，即某个叶子中，该分类赝本的占比
	# result=clf.predict_proba([[5,1,3]])  #计算属于每个类的概率
	# print result
	
	#打印图片
	createPic(clf)


def createPic(clf):
	import pydotplus
	# dot_data = tree.export_graphviz(clf, out_file=None) 
	dot_data = tree.export_graphviz(clf, out_file=None,  #指定不同类别颜色
	                         filled=True, rounded=True,  
	                         special_characters=True) 

	graph = pydotplus.graph_from_dot_data(dot_data) 
	graph.write_png("sciki.png")


# 保存决策树
def saveTree(tree):
	filename=urlSave
	pickle.dump(tree,open(filename,'wb'))

#加载决策树
def loadTree():	#加载模型
	filename=urlSave
	load_model = pickle.load(open(filename,'rb'))
	return load_model


def loadTxt(url):
	dataframe = pandas.read_csv(url)

	array = dataframe.values
	x=array[:,0:40]  
	y = array[:,40] 

	#75%训练  25%测试
	X_train,X_test,y_train,y_test = model_selection.train_test_split(x,y,test_size=0.25)

	# #创建决策树
	clf=tree.DecisionTreeClassifier() #默认Gini基尼不纯度 entropy 采用ID3算法criterion='entropy'
	# #拟合
	clf =clf.fit(X_train,y_train)
	# #输出每个特征的重要程度
	print("特征重要程度",clf.feature_importances_)
	result=clf.score(X_test,y_test)
	print("预测重合度:",result)

	# print x[0][3]
	#保存决策树
	# saveTree(clf)

	# clf=loadTree()
	# print clf.feature_importances_
	#结果预测
	# fen=clf.predict([[1517277600,27,270,201801301000,111160580,0.31,0.0,27,14,27,16,95.35,27,100.0,0,0,0,0,0.0,0,0.0,1,15,3,5.56,0,0,0,0.0,2674,6540,1,1,100.0,396,4.23,4.23,4.23,0.06,25]])
	# print "样本分类",fen
	
	#打印图片
	createPic(clf)



def main():
	# saveDataToStary()
	# pic()
	# test()
	url=".\work\data\ecicikit.txt";
	loadTxt(url)

if __name__ == '__main__':
	main()